package 代码随想2._6栈与队列;

/**
 * @author XXX
 * @date 2024-01-17 18:51
 */

import java.util.Stack;

/**
 * https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
 */
public class _5逆波兰表达式求值 {
    public int evalRPN(String[] tokens) {
        Stack<Integer> nums = new Stack<>();
        for(String s : tokens){
            if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/")){
                int val = cal(nums.pop(),nums.pop(),s);
                nums.push(val);
            }else {
                nums.push(Integer.parseInt(s));
            }
        }
        return nums.pop();
    }

    int cal(int right , int left, String op){
        int ans = 0;
        switch (op){
            case "+":
                ans =left + right;
                break;
            case "-":
                ans = left - right;
                break;
            case "*":
                ans = left * right;
                break;
            case "/":
                ans = left / right;
                break;
        }
        return ans;
    }
}
